#第12章 文件
# ! /usr/bin/python
# -*-coding:UTF-8-*-
path = 'h:/test.txt'
#需要确保该文件存在，否则会报异常
file = open(path)
print('文件名是：',file.name)

#使用相对路径
#创建一个文件，如果存在就覆盖，不存在则新建
import os
path = './testfile'
if not os.path.exists(path):
    os.mkdir(path)
path = './testfile/test2.txt'
file = open(path,'w')
print('文件名是：',file.name)

#read and write
_path = './testfile/test.txt'
_file = open(_path,'w+')
#在文件中写入：“hello world!welcome”
_file.write("hello world!welcome")
#注意：对于新写入文件的内容，只有在重新打开后才可以读取到
_file = open(_path,'r')
print('file.read(12)=',_file.read(12))
#追加写入
_file = open(_path,'a')
_file.write('!I am coming!')
_file = open(_path)
print('_file.read()=',_file.read())
#添加换行符，增加换行
_file = open(_path,'a')
_file.write('\nyou am coming too!')
_file = open(_path)
print('_file.read()=',_file.read())
# copy文件
def copyFile(source, target):
    file = open(source, 'rb')
    file2 = open(target, 'wb')
    # file2 = open(target, 'ab')
    _len = file2.write(file.read())
    print('写入大小：', _len)
path = "h:/1.mp4"
path2 = "h:/test.mp4"
# copyFile(path,path2)

#行操作
print('-----------行操作------------')
file = open("./testfile/test.txt","w")
file.write('hello world\n')
file = open("./testfile/test.txt","a")
file.write('welcome')
file = open('./testfile/test.txt','r')
# print('file.readline()=',file.readline())
print('file.readlines()=',file.readlines())
#writelines
print('-----------writelines------------')
file = open("./testfile/test.txt","w")
str_list = ['hello world\n','welcome!']
file.writelines(str_list)
file = open('./testfile/test.txt','r')
print(file.read())
file = open('./testfile/test.txt','r')
print(file.readlines())

#关闭文件
print('-----------close()------------')
try:
    file = open("./testfile/test.txt","w")
    file.writelines(['hello world\n','welcome'])
except Exception as e:
    print(e)
finally:
    if file:
        file.close()

#使用with语句
print('-----------使用with语句------------')
with open("./testfile/test.txt","w") as file_123:
    file_123.writelines(['hello world\n', 'welcome'])

#使用rename语句
print('-----------使用rename语句------------')
# file = open("./test.txt","w")
# file.close()
# 上下两种方法都可以
open("./test.txt","w")
import os
os.rename('test.txt','test123.txt')

#删除文件
print('-----------删除文件------------')
try:
    os.remove('./test123.txt')
except Exception:
    print('文件不存在！')

#迭代文件
print('-----------迭代文件------------')
#按字节处理
file = open('./testfile/test.txt')
while True:
    c_str = file.read(1)
    print(c_str)
    if not c_str:
        break
#按行处理
file = open('./test.txt',encoding='UTF-8')
while True:
    c_str = file.readline()
    print(c_str)
    if not c_str:
        break

#使用fileeinput实现文件懒（延迟）加载
path = './test.txt'
import fileinput
for line in fileinput.input(path,openhook=fileinput.hook_encoded('UTF-8')):
    print(line)

#文件迭代器
file = open('./test.txt',encoding='UTF-8')
for line in file:
    print(line)
file.close()

#StringIO
from io import StringIO
strio = StringIO()
strio.write('hello world')
print(strio.getvalue())

#使用str对StringIO进行初始化
strio = StringIO('hello\nworld\nI\'m coming')
while True:
    line = strio.readline()
    if line:
        print(line.strip())
    else:
        break

import pickle
str = 'hello\nworld\nwelcome'
print(pickle.dumps(str))
fileName = open('dump.txt','wb')
#以下两种写法都正确
#写法1
# fileName.write(pickle.dumps(str))
#写法2
pickle.dump(str,fileName)
fileName.close()
fileName = open('dump.txt','rb')
# 输出为byte
# print(fileName.read())
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte
# print(fileName.read().decode('utf-8'))
# 正确写法
print(pickle.load(fileName))

print('---------------Json序列化实例-------------------')
#Json序列化实例
import json
data = {'name':'小明','age':23,'sex':'男'}
#如果不加ensure_ascii=False 返回的json数据中文显示有问题，
#变成\uXXX的形式。这是因为中文以unicode 编码了，
#而默认是以ASCII解析的，中文不在ASCII编码中，所以无法显示
str = json.dumps(data,ensure_ascii=False)
print('json str = ',str)
print('python dict = ',data)
data2 = json.loads(str)
print('covert python dict = ',data)
print('---------------Json格式文件序列化-------------------')
#Json格式文件序列化
with open('dump.txt','w') as f:
    json.dump(data,f)

with open('dump.txt') as f:
    data = json.load(f)
    print(data)

print('---------------调试-------------------')
#调试
str = '1 2\t 3\n 4'
print(str)
str = repr('1 2\t 3\n 4')
print(str)


print('---------------以下为测试代码-------------------')
import os
# with open('test.txt') as _file:
# 上面句话是没用的，反而加上这句话后，下面的语句会报错，提示文件被占用
# 因为文件一直处于只读打开方式而没有关闭
# 所以，由此可见，给文件重命名是不需要打开文件的
# with open('_test.txt','w') as _file:
# 以编辑模式打开后再重命名，同样会报错文件被占用
# 同时注意，以编辑模式打开文件时，首先会将文件中原有的内容删除
# 直接写文件名，代表的是当前路径下
#os.rename('_test.txt','test.txt')
# 带路径重命名同样也是可行的
# os.rename('./testfile/test.txt','./testfile/_test.txt')
# os.rename('./testfile/_test.txt','./testfile/test.txt')

# with open('./testfile/test2.txt') as _file:
#     print(_file.read())

with open('./testfile/test.txt') as _file:
    for line in _file.readlines():
        # print(line)#这样每行结尾会有空格
        print(line.rstrip())#这样可以去掉结尾的空格